package com.alpesressources.comexpert;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.alpesressources.comexpert.bo.IObject;
import com.alpesressources.comexpert.bo.request.AuthenticateRequest;
import com.alpesressources.comexpert.bo.response.AuthenticateResponse;
import com.alpesressources.comexpert.bo.response.ErrorResponse;
import com.alpesressources.comexpert.bo.response.Response;
import com.alpesressources.comexpert.bo.response.ErrorResponse.EnumErrorCode;
import com.alpesressources.comexpert.bo.response.ResponseObject.EnumResult;
import com.alpesressources.comexpert.dao.DaoManager;
import com.alpesressources.comexpert.exception.DaoException;
import com.alpesressources.comexpert.util.MyJsonSerializer;

public class Authentification extends AAction {

	private static Logger logger = Logger.getLogger(Authentification.class);
	private String token;

	@Override
	public void processGet(ServletConfig config,
			HashMap<String, Object> queryString, HttpServletResponse response)
			throws ServletException, IOException {
	}

	@Override
	public void processPost(ServletConfig config,
			HashMap<String, Object> queryString, IObject postRequest,
			HttpServletResponse response) throws ServletException, IOException {
		AuthenticateRequest authenticateRequest = (AuthenticateRequest) postRequest;

		AuthenticateResponse authenticateResponse = new AuthenticateResponse();
		authenticateResponse.setUserName(authenticateRequest.getUserName());

		if (authenticateRequest.getUserName() != null
				&& authenticateRequest.getPassWord() != null) {
			
			try {
				DaoManager daoManager=new DaoManager(queryString.get("dossier").toString());
				
				token=daoManager.authenticate(authenticateRequest.getUserName(), authenticateRequest.getPassWord());
				
				authenticateResponse.setResult(EnumResult.OK);
				authenticateResponse.setToken(token);
				authenticateResponse.setUserName(authenticateRequest.getUserName());
				
			} catch (DaoException e) {
				authenticateResponse.setResult(EnumResult.NOK);
				
				logger.error(e);
			}
		} else {
			authenticateResponse.setResult(EnumResult.NOK);

			logger.info("Authentification failed: all required fields are not present in the request");
		}

		logger.info(authenticateResponse);

		Response r = new Response();
		ErrorResponse errorResponse = new ErrorResponse();

		errorResponse.setErrorCode(EnumErrorCode.NO_ERROR);
		r.setErrorResponse(errorResponse);

		r.getData().add(authenticateResponse);

		MyJsonSerializer myJsonSerializer = new MyJsonSerializer();

		response.getOutputStream().write(
				myJsonSerializer.serialize(r).getBytes());
	}

	@Override
	public String getToken() {
		return token;
	}

	@Override
	public Class<?> getObjectClass() {
		return AuthenticateRequest.class;
	}

}
